package hy;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Test1 {
    static Jedis j=new Jedis("192.168.188.100",6379);
    @Test
    public void test1(){
        j.set("address","南京");
        System.out.println(j.get("address"));
        j.incrBy("age",20);
        System.out.println(j.get("age"));
        Set<String>keys= j.keys("*");
        keys.forEach(t->{
            System.out.println(t);
            //System.out.println(j.get(t));
        });

//        for(String s:keys){
//            System.out.println(s);
//        }
        Map<String,String> m=new HashMap<>();
        m.put("a1","11");
        m.put("a2","22");
        j.hmset("users",m);
        System.out.println(j.hgetAll("users"));
    }


    @Test
    public void transac()throws Exception{
        j.set("money","960");//可用额度
        j.set("debt","40");//欠债

        int consume=10;
        j.watch("money");
        Thread.sleep(10000);
        int money=Integer.parseInt(j.get("money"));//获取可用额度
        if(money<consume){
            j.unwatch();
            System.out.println("额度不够");
            return;
        }
        System.out.println("===================事务开启=================");
        Transaction t=j.multi();
        t.incrBy("debt",consume);
        t.decrBy("money",consume);
        List list=t.exec();
        if(list==null){
            System.out.println("事务失败");
        }
        j.unwatch();
        System.out.println("事务结束，余额："+j.get("money")+",欠账："+j.get("debt"));
    }
    @Test
    public void master_slave(){
        Jedis master=new Jedis("192.168.188.100",6379);
        Jedis slave=new Jedis("192.168.188.100",6380);
        slave.slaveof("192.168.188.100",6379);
        master.set("driver","com.mysql.driver");
        System.out.println(slave.get("driver"));
    }
}
